package com.mikhailenko.transportMVC.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mikhailenko.transportMVC.exeption.UserNotFoundExeption;
import com.mikhailenko.transportMVC.model.User;
import com.mikhailenko.transportMVC.repository.UserRepository;
import com.mikhailenko.transportMVC.service.UserService;

@Service
public class UserServiceImpl implements UserService{
	
	@Resource
    private UserRepository userRepository;

	@Override
	@Transactional
	public User create(User user) {
		User createdUser = user;
		return userRepository.saveAndFlush(createdUser);
	}

	@Override
	@Transactional(rollbackFor=UserNotFoundExeption.class)
	public User delete(int id) throws UserNotFoundExeption {
		User deletedUser = userRepository.findOne(id);
		
		if(deletedUser == null){
			throw new UserNotFoundExeption();
		}
		
		userRepository.delete(id);
		return deletedUser;
	}

	@Override
	@Transactional
	public List<User> findAll() {
		return userRepository.findAll();
	}

	@Override
	@Transactional(rollbackFor=UserNotFoundExeption.class)
	public User update(User user) throws UserNotFoundExeption {
		User updatedUser = userRepository.findOne(user.getUserID());
		
		if (updatedUser == null){
			throw new UserNotFoundExeption();
		}
		
		updatedUser.setUsername(user.getUsername());
		updatedUser.setFullName(user.getFullName());
		updatedUser.setEmail(user.getEmail());
		updatedUser.setAddress(user.getAddress());
		updatedUser.setPassword(user.getPassword());
		updatedUser.setTelephone(user.getTelephone());
		updatedUser.setRole(user.getRole());
		return updatedUser;
	}

	@Override
	@Transactional
	public User findById(int id) {
		return userRepository.findOne(id);
	}
 
 
}
